require 'rho/rhocontroller'
require 'helpers/browser_helper'
require 'json'
require 'WebServices/base_service'

class SessionController < Rho::RhoController
  include BrowserHelper

	def post_login
    @username = @params["username"]
    @password = @params["password"]

    url = "http://10.10.10.154:3000/sign_in"
    param_string = "{user:{user_name:#{@username},password:'#{@password}'}}"

    cookie = @params[:cookie]

    response = Rho::AsyncHttp.post(
    :url => url,
    :headers => {"content-type" => "application/json"},
    :body => param_string
    )

    $user = response["body"]["user"]
      
    status =  response["body"]["status"]

    if @username and @password
      begin
        SyncEngine.login(@username, @password,
        (url_for :action => :login_callback) )

        @response['headers']['Wait-Page'] = 'true'
        render :action => :wait
      rescue Rho::RhoError => e
        @msg = e.message
        render :action => :login
      end
    else
      @msg = Rho::RhoError.err_message(Rho::RhoError::ERR_UNATHORIZED) unless @msg && @msg.length > 0
      render :action => :login
    end
	end

	def login
    @msg = @params['msg']
	  if $user == nil || SyncEngine::logged_in == false
      SyncEngine.logout
	  end
	  
		render :action => :login
	end
	
  def login_callback
    
    username = $user['user_name']
    p "#{@params.inspect}"
    error_code = @params['error_code'].to_i
    if error_code == 0
      # run sync if we were successful
      #WebView.navigate Rho::RhoConfig.options_path
      #redirect :action => :index, :controller => :Student
      
     
      if  $user['role'] == 'teacher'
        WebView.navigate url_for(:action => :index, :controller => :Teacher)
      else
        WebView.navigate url_for(:action => :index, :controller => :Student)
      end
     
      #SyncEngine.dosync
    else
      if error_code == Rho::RhoError::ERR_CUSTOMSYNCSERVER
        @msg = @params['error_message']
      end
  
      if not @msg or @msg.length == 0   
        @msg = Rho::RhoError.new(error_code).message
      end
  
      WebView.navigate( 
        url_for(:action => :login, :query => {:msg => @msg}) 
      )
    end  
  end
  
  def logout
      SyncEngine.logout
      
      @msg = "You have been logged out."
      render :action => :login
    end    
  
  def register
    render :action => :register
  end

  def do_register
    $sign_up_info = $sign_up_info || {}
    $sign_up_info.merge!(@params)

    if $sign_up_info['type'] == 'student'
      url = BaseService::SERVER_URL
      param_string = {
        :user => {
          :user_name => $sign_up_info['username'],
          :password => $sign_up_info['password'],
          :role => $sign_up_info['type'],
          :name => $sign_up_info['name']          
        }
      }.to_json
      Rho::AsyncHttp.post(
        :url => "#{url}/sign_up",
        :headers => {"content-type" => "application/json"},
        :body => param_string 
      )['body'] || []
      redirect :action => :login  
    else
      redirect :controller => :Teacher, :action => :select_grade  
    end    
    
  end
end
